package com.tg.paw.gateway.filter;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.tg.paw.gateway.util.JWTUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

/**
 * AuthorizeFilter
 *
 * @author Rubble
 * @date 2020/6/12
 */
@Slf4j
@Configuration
@EnableConfigurationProperties(JwtProperties.class)
public class AuthorizeFilter implements GlobalFilter, Ordered {

    @Autowired
    private JwtProperties jwtProperties;

    public static final String TOKEN ="Token";

    public static final String Authorization ="Authorization";

    public static final String USERNAME ="userName";


    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest serverHttpRequest = exchange.getRequest();
        ServerHttpResponse serverHttpResponse = exchange.getResponse();
        String uri = serverHttpRequest.getURI().getPath();
        log.info("========== gateway uri: "+uri);

        //  检查白名单（配置）
        AntPathMatcher pathMatcher = new AntPathMatcher();
        for(String pattern: jwtProperties.getIgnoreUrls()){
            if(pathMatcher.match(pattern,uri)){
                return chain.filter(exchange);
            }
        }

        String token = serverHttpRequest.getHeaders().getFirst(Authorization);
        if(StringUtils.isEmpty(token)){
            token = serverHttpRequest.getHeaders().getFirst(TOKEN);
        }
        if (StringUtils.isBlank(token)) {
            serverHttpResponse.setStatusCode(HttpStatus.UNAUTHORIZED);
            return getVoidMono(serverHttpResponse,"请求无token");
        }
        try {
            JWTUtil.verifyToken(token, jwtProperties.getSecretKey());
        } catch (Exception ex) {
            return getVoidMono(serverHttpResponse, "无效的token");
        }

        String userName = JWTUtil.getUserInfo(token);

        ServerHttpRequest mutableReq = serverHttpRequest.mutate().header(USERNAME, userName).build();
        ServerWebExchange mutableExchange = exchange.mutate().request(mutableReq).build();

        return chain.filter(mutableExchange);
    }

    private Mono<Void> getVoidMono(ServerHttpResponse serverHttpResponse,String messageStr) {
        serverHttpResponse.getHeaders().add("Content-Type", "application/json;charset=UTF-8");
        JSONObject message = new JSONObject();
        message.put("message", messageStr);
        message.put("code", 401);
        DataBuffer dataBuffer = serverHttpResponse.bufferFactory().wrap(JSON.toJSONString(message).getBytes());
        return serverHttpResponse.writeWith(Flux.just(dataBuffer));
    }

    @Override
    public int getOrder() {
        return -100;
    }
}
